<template>
  <div class="rich-editor">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden;"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

interface Props {
  value?: string
}

interface Emits {
  (e: 'update:value', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  value: ''
})

const emit = defineEmits<Emits>()

const editorRef = shallowRef()
const mode = 'default'

const valueHtml = ref('')

watch(
  () => props.value,
  (newVal) => {
    valueHtml.value = newVal
  },
  { immediate: true }
)

watch(
  valueHtml,
  (newVal) => {
    emit('update:value', newVal)
  }
)

const toolbarConfig = {
  excludeKeys: [
    'group-video',
    'fullScreen'
  ]
}

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/upload/image',
      fieldName: 'file',
      meta: {},
      metaWithUrl: false,
      withCredentials: true,
      timeout: 15 * 1000,
      onBeforeUpload: (file: File) => {
        console.log('onBeforeUpload', file)
        return file
      },
      onProgress: (progress: number) => {
        console.log('onProgress', progress)
      },
      onSuccess: (file: File, res: any) => {
        console.log('onSuccess', file, res)
      },
      onFailed: (file: File, res: any) => {
        console.log('onFailed', file, res)
      },
      onError: (file: File, err: any, res: any) => {
        console.log('onError', file, err, res)
      },
      customInsert: (res: any, insertFn: Function) => {
        const url = res?.data?.url || res?.url
        if (url) {
          insertFn(url)
        }
      }
    }
  }
}

const handleCreated = (editor: any) => {
  editorRef.value = editor
  console.log('created', editor)
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
.rich-editor {
  border: 1px solid #ccc;
  z-index: 100;
}
</style>